from flask import Flask, render_template, escape, request, session, redirect, url_for, flash
import random
import geo
import citycode
import weather as we
import pandas as pd

app = Flask(__name__)

app.config['SECRET_KEY']='iamkey' #猜数字游戏用配置，设置session的secret key

dict=citycode.read_excel()

# 高德步行规划
def direction(key, start_address, end_address):
    """  方向获取  """
    start = geo.geocode(key, start_address)['geocodes'][0]['location']
    end = geo.geocode(key, end_address)['geocodes'][0]['location']
    results = geo.walk(key, start, end)
    df = pd.json_normalize(results['route']['paths'][0]['steps'])
    return df


def total_distance(df):
    """  总路程计算  """
    distance = df['distance'].to_list()
    sum_num = 0
    for i in distance:
        sum_num += int(i)
    return sum_num


def total_time(df):
    """  总时间计算  """
    duration = df['duration'].to_list()
    sum_num = 0
    for i in duration:
        sum_num += int(i)
    return sum_num // 60


def weather_req(key, city):

    city =(dict[(city)][1])
    results = we.weather(key, city)

    df = pd.json_normalize(results)['lives']
    return df

# 日志系统
def log_request(req: 'flask_request', res: str) -> None:
    """ 日志系统 """
    with open('flask.log','a') as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log, sep='|')


# #登陆系统页面
# @app.route('/login', methods=('GET', 'POST'))
# def index(id=None):
#     """ 登录系统 """
#     global name, login
#     # 然后发起一个post请求
#     if request.method == 'POST':
#         # 判断请求的账户和密码，如果判断成功，那么跳到下一个页面去
#         if request.form.get('account') == 'admin' and request.form.get('pwd') == '123456':
#             login = 'success'
#             name = 'admin'
#             return render_template('entry.html', name=name, login=login)
#         # 输入了错误的账户和密码请求失败则跳转到失败页面
#         else:
#             login = 'fail'
#             return render_template('login_fail.html')
#     return render_template('login.html')


# 首页页面
@app.route('/')
def index():
    """ 首页 """
    title = '欢迎来到我的学习博客:D'
    return render_template('index.html',
                           the_title = title,
                           )


# 功能展示页
# 1、高德api路径规划 - 步行路径规划
@app.route('/walk_intro')
def walk_intro():
    """ 高德api路径规划 - 步行路径规划介绍 """
    title = '高德API路径规划 - 步行路径规划'
    return render_template('walk_intro.html',
                           the_title = title,
                           )

@app.route('/api_walk')
def api_walk():
    """ 高德api路径规划 - 步行路径规划输入数据 """
    title = '来看看怎么走到你想去的目的地吧！'
    return render_template('api_walk.html',
                           the_title = title,
                           )

@app.route('/walk_results', methods=(['POST']))
def walk_results() -> 'html':
    print('e')
    """ 高德api路径规划 - 步行路径规划调用结果演示 """
    key = request.form['key']
    #  实在没有用我的也不是不行：‘a9758bee89912716bcdb624bc0338c84’
    start_address = request.form['start']
    end_address = request.form['end']
    title = '查询结果'
    df = direction(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    the_distance = total_distance(df)
    the_time = total_time(df)
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('walk_results.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           the_html_table=results.to_html(index=False),
                           the_total_walk=the_distance,
                           the_total_walk_time=the_time, )


# 2、猜数字小游戏
@app.route('/guess_number_intro')
def number_intro():
    """ 猜数字小游戏介绍 """
    title = '猜数字小游戏;)'
    return render_template('guess_number_intro.html',
                           the_title = title,
                           )

@app.route('/guess_number_entry')
def number_entry():
    """ 猜数字小游戏入口 """
    title = '开始猜吧！'
    return render_template('guess_number_entry.html',
                           the_title = title,
                           )

@app.route('/guess_number', methods=['GET','POST'])
def guess_numebr():
    """ 猜数字小游戏 """
    if request.method == 'GET':
        session['chances'] = 10 #机会次数
        session['set_number'] = random.randint(1, 1000) #答案
        session['number1'] = 0 #起始范围最小数
        session['number2'] = 1000 #起始范围最大数
        return render_template('guess_number.html')
    elif request.form.get('guess-number') == '':
        flash('请输入一个整数！')
        return render_template('guess_number.html')
    else:
        session['chances'] -= 1
        print('要猜的数字：', session['set_number'])
        guess_number = int(request.form.get('guess-number'))

        if guess_number > session['set_number']:
            session['number2'] = guess_number
            if session.get('chances') == 0:
               flash('Game Over！要不再玩一次？')
               return redirect(url_for('index'))
            flash('数字太大了，在{}~{}之中再猜一个！'.format(session['number1'], session['number2']))
            return render_template('guess_number.html')

        if guess_number < session['set_number']:
            session['number1'] = guess_number
            if session.get('chances') == 0:
               flash('Game Over！要不再玩一次？')
               return redirect(url_for('index'))
            flash('数字太小了，在{}~{}之中再猜一个！'.format(session['number1'], session['number2']))
            return render_template('guess_number.html')

        else:
            flash('恭喜你用了{}次机会就猜对了数字！'.format(10 - session['chances']))
            return render_template('guess_number.html')


# 3、天气查询
@app.route('/weather_intro')
def weather_intro():
    """ 天气查询功能首页 """
    title = '高德API天气查询'
    return render_template('weather_intro.html',
                           the_title = title,
                           )

@app.route('/weather')
def weather():
    """ 天气查询功能首页 """
    title = '看看今天又几度'
    return render_template('weather.html',
                           the_title = title,
                           )

@app.route('/weather_results', methods=(['POST']))
def weather_results() -> 'html':
    """ 高德API天气查询调用 """
    key = request.form['key']
    city = request.form['city']
    title = '今天的天气是这样'
    df = weather_req(key, city)
    print(df)
    results = df[0][0]
    #results.columns = ['城市','天气','气温','风向','风力','湿度']
    place = results['city']
    tianqi = results['weather']
    log_request(request, place+'  '+tianqi)
    base_data_model=pd.DataFrame([results])
    #base_data_model=base_data_model.rename(columns={'province': '省份'})
    #base_data_model=base_data_model.rename(columns={'city': '城市'})
    #base_data_model=base_data_model.rename(columns={'weather': '天气'})
    #base_data_model=base_data_model.rename(columns={'temperature': '气温'})
    #base_data_model=base_data_model.rename(columns={'winddirection': '风向'})
    #base_data_model=base_data_model.rename(columns={'windpower': '风力'})
    #base_data_model=base_data_model.rename(columns={'humidity': '湿度'})
    #base_data_model.columns =  ['城市','天气','气温','风向','风力','湿度']
    return render_template('weather_results.html',
                           the_title = title,
                           the_city = city,
                           the_results = results,
                           the_html_table =base_data_model.to_html(index=False)
                           )


# 日志系统页面
@app.route('/view_log')
def view_log() -> 'html':
    contents=[]
    with open('flask.log', 'r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ('用户输入数据', '远程机器的IP地址', '用户代理', '查询结果')
    return render_template('view_log.html',
                           the_title = '日志系统',
                           row_titles = titles,
                           the_data = contents,
                           )




if __name__ == '__main__':
    app.run(debug=True)
